<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import_excel'" type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="exportExcel">excel导出</el-button>
          <el-button v-allow="'add'" type="primary" size="small" @click="hAdd">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop: 'timeOfEntry', order: 'descending'}">
          <el-table-column label="序号" type="index" width="80" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="用户头像" width="120">
            <template #default="{row}">
              <img
                v-imgerror="require('@/assets/common/head.jpg')"
                :src="row.staffPhoto"
                alt=""
                style="height:100px"
                @click="showCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template slot-scope="scope">
              {{ formatDate(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next,total"
            :current-page="q.page"
            :page-size="q.size"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog :visible.sync="showDialog" title="新增员工">
        <addor-edit v-if="showDialog" @success="hSuccess" @close="showDialog=false" />
      </el-dialog>
      <el-dialog :visible.sync="showCodeDialog" title="员工头像二维码">
        <el-row type="flex" justify="center">
          <canvas ref="qrCodeCanvas" />
        </el-row>
      </el-dialog>
      <el-dialog :visible.sync="showRoleDialog" title="分配角色">
        <assign-role
          v-if="showRoleDialog"
          :cur-id="curId"
          @close="showRoleDialog=false"
        />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import addorEdit from './empDialog'
import QRCode from 'qrcode'
import employeeEnum from '@/constant/employees'
import { delEmployee, getEmployeeList } from '@/api/employees'
import { enTransZh } from '@/utils'
import AssignRole from './assignRole.vue'
const hireType = {}
employeeEnum.hireType.forEach(item => {
  hireType[item.id] = item.value
})
export default {
  components: {
    'addor-edit': addorEdit,
    AssignRole
  },
  data() {
    return {
      list: [],
      q: {
        page: 1,
        size: 10
      },
      total: 10,
      showDialog: false,
      showCodeDialog: false,
      showRoleDialog: false,
      curId: ''
    }
  },
  created() {
    this.loadEmpolyeeList()
  },
  methods: {
    hAssignRole(id) {
      this.showRoleDialog = true
      this.curId = id
    },
    showCode(url) {
      if (url) {
        this.showCodeDialog = true
        this.$nextTick(() => {
          const canvas = this.$refs.qrCodeCanvas
          QRCode.toCanvas(canvas, url)
        })
      } else {
        this.$message.error('请上传用户头像')
      }
    },
    exportExcel() {
      import('@/vendor/Export2Excel').then(async excel => {
        // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
        // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        // const list = this.list
        // const data = this.formatJson(filterVal, list)
        await this.loadEmpolyeeList()
        const { tHeader, data } = enTransZh(this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
      })
    },
    async loadEmpolyeeList() {
      try {
        const res = await getEmployeeList(this.q)
        // console.log('getEmployeeList', res)
        if (res.code === 10000) {
          this.list = res.data.rows
          this.total = res.data.total
        }
        // 保存数据
      } catch (err) {
        console.log('getEmployeeList', err)
      }
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.q.page = val
      this.loadEmpolyeeList()
    },
    formatDate(id) {
      return hireType[id] || '未知'
    },
    hDel(id) {
      this.$confirm('确认删除改员工?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delEmployee(id)
        if (res.code === 10000) {
          console.log(res)
          this.$message.success(res.message)
          if (this.list.length === 1) {
            this.q.page--
            if (this.q.page <= 0) {
              this.q.page = 1
            }
          }
          this.loadEmpolyeeList()
        }
      }).catch((error) => {
        this.$message.error(error)
      })
    },
    hAdd() {
      this.showDialog = true
    },
    hSuccess() {
      this.showDialog = false
      this.total++
      this.q.page = Math.ceil(this.total / this.q.size)
      this.loadEmpolyeeList()
    }

  }
}
</script>
